/**
 * 部门接口。
 */
var express = require("express");
var router = express.Router();
var RoleAccess = require("../../../../models/RoleAccess.ts");
var _ = require("lodash");
var encrypt = require("../../enoadEncrypt");
var decrypt = require("../../enoadDecrypt");
const ObjectAcc = require("../../../../models/ObjectConfig.ts"); //拿到总配置信息。

//获取所有权限。
//@Api(name="/rest/role/fetchAccess")
router.post("/role/fetchAccess", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  try {
    ObjectAcc.getObjects(dataBaseName,function (err, configs) {
      if (err) {
        configs = [];
      }
      let data = new Array();
      data.push({
        title: "后端配置权限",
        key: "system_config",
      });
      data.push({
        title: "首页卡片权限",
        key: "title_cards",
        children: [
          {
            title: "新建首页卡片",
            key: "title_cards_create",
          },
          {
            title: "编辑首页卡片",
            key: "title_cards_edit",
          },
          {
            title: "删除首页卡片",
            key: "title_cards_delete",
          },
          {
            title: "查询首页卡片",
            key: "title_cards_select",
          },
        ],
      });
      let allEntitys = new Array();
      _.forEach(configs, (config) => {
        //拿到所有实体。apikey和name。
        allEntitys.push({
          title: config.name,
          key: config.apiKey,
          children: [
            {
              title: "新建" + config.name,
              key: config.apiKey + "_create",
            },
            {
              title: "编辑" + config.name,
              key: config.apiKey + "_edit",
            },
            {
              title: "删除" + config.name,
              key: config.apiKey + "_delete",
            },
            {
              title: "查询" + config.name,
              key: config.apiKey + "_select",
            },
            {
              title: "上传" + config.name,
              key: config.apiKey + "_upload",
            },
            {
              title: "下载" + config.name,
              key: config.apiKey + "_download",
            },
          ],
        });
      });
      if (allEntitys.length > 0) {
        data.push({
          title: "所有实体权限",
          key: "allEntitys",
          children: allEntitys,
        });
      }
      let response = {
        code: 200,
        msg: "OK",
        data: data,
      };
      res.send(response);
    });
  } catch (error) {
    res.send(error);
  }
});

/**
 * 权限
 */
//@Api(name="/rest/role/create")
router.post("/role/create", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  const body = req.body;
  var role = new RoleAccess({
    name: body.name,
    admin: body.admin || false,
    access: body.access,
  });
  role.save(dataBaseName,function (err, result) {
    if (err) {
      res.send({
        code: 201, // 0 表示处理成功，1 表示处理失败
        msg: "服务器错误，请联系管理员", // 状态的描述
        data: null, // 需要响应给客户端的数据
      });
    }
    res.send({
      code: 200, // 0 表示处理成功，1 表示处理失败
      msg: "角色创建成功", // 状态的描述
      data: result, // 需要响应给客户端的数据
    });
  });
});

//@Api(name="/rest/role/update")
router.post("/role/update", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  const body = req.body;
  const id = body._id;
  var role = new RoleAccess({
    name: body.name,
    admin: body.admin,
    access: body.access,
  });
  RoleAccess.update(id, role,dataBaseName, function (err, newDep) {
    if (err) {
      res.send({
        code: 201, // 0 表示处理成功，1 表示处理失败
        msg: "服务器错误，请联系管理员", // 状态的描述
        data: null, // 需要响应给客户端的数据
      });
    } else {
      res.send({
        code: 200, // 0 表示处理成功，1 表示处理失败
        msg: "更新成功", // 状态的描述
        data: newDep, // 需要响应给客户端的数据
      });
    }
  });
});

//@Api(name="/rest/role/delete")
router.post("/role/delete", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  const body = req.body;
  const ids = body.ids || []; //获取需要删除的id组。
  let allPromise = [];
  _.forEach(ids, (id) => {
    allPromise.push(
      new Promise((resolve, reject) => {
        RoleAccess.deleteById(id,dataBaseName, (err) => {
          if (err) {
            resolve({ id, status: false });
          } else {
            resolve({ id, status: true });
          }
        });
      })
    );
  });
  Promise.all(allPromise).then((allStaus) => {
    let data = [];
    _.forEach(allStaus, (item) => {
      data.push({
        id: item.id,
        msg: item.status ? "删除成功" : "删除失败",
      });
    });
    res.send({
      code: 200, // 0 表示处理成功，1 表示处理失败
      msg: "操作完成", // 状态的描述
      data,
    });
  });
});

//获取用户所有数据。
//@Api(name="/rest/role/fetchAllRoles")
router.post("/role/fetchAllRoles", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  RoleAccess.getAllData(dataBaseName,(err, all) => {
    if (err) {
      res.send({
        code: 201,
        msg: "服务器错误，请联系管理员",
        data: null,
      });
    } else {
      res.send({
        code: 200,
        msg: "查询成功",
        data: all,
      });
    }
  });
});

module.exports = router;
